/*******************************************************************************
 * Copyright 2011, 2012 Chris Banes.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.handmark.pulltorefresh.library;
 

import com.handmark.pulltorefresh.library.ex.OnHorizontalScrollListener;

import lib.pacificapp.framework.R;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.PointF; 
import android.util.AttributeSet;
import android.util.DisplayMetrics; 
import android.view.MotionEvent;
import android.view.View; 
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

public class PullToRefreshHorizontalScrollView extends PullToRefreshBase<HorizontalScrollView> {
    public interface OnPageListener{
    	void onPage(int pageId);
    }
    
    private OnPageListener mOnPageListener;
    public void setOnPageListener(OnPageListener listener){
    	  mOnPageListener=listener;
    }
	public PullToRefreshHorizontalScrollView(Context context) {
		super(context);
	}

	public PullToRefreshHorizontalScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public PullToRefreshHorizontalScrollView(Context context, Mode mode) {
		super(context, mode);
	}

	public PullToRefreshHorizontalScrollView(Context context, Mode mode, AnimationStyle style) {
		super(context, mode, style);
	}

	@Override
	public final Orientation getPullToRefreshScrollDirection() {
		return Orientation.HORIZONTAL;
	}
	public MyHorizontalScrollView scrollView=null;
	public void removePage(int i){
		  scrollView.removePage(i);
	}
	@Override
	 protected HorizontalScrollView createRefreshableView(Context context, AttributeSet attrs) {
		 
//		if (VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD) {
//			scrollView = new InternalHorizontalScrollViewSDK9(context, attrs);
//		} else {
			 scrollView = new MyHorizontalScrollView(context, attrs); 
			 scrollView.setHorizontalScrollBarEnabled(false);
			 scrollView.setScrollBarSize(0);
			 scrollView.setScrollBarStyle(0); 
			 
		//}
		
		scrollView.setId(R.id.scrollview);
		return scrollView;
	}

	@Override
	protected boolean isReadyForPullStart() {
		return mRefreshableView.getScrollX() == 0;
	}

	@Override
	protected boolean isReadyForPullEnd() {
		View scrollViewChild = mRefreshableView.getChildAt(0);
		if (null != scrollViewChild) {
			return mRefreshableView.getScrollX() >= (scrollViewChild.getWidth() - getWidth());
		}
		return false;
	}

	@TargetApi(9)
	final class InternalHorizontalScrollViewSDK9 extends HorizontalScrollView {

		public InternalHorizontalScrollViewSDK9(Context context, AttributeSet attrs) {
			super(context, attrs);
		}

		@Override
		protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX,
				int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {

			final boolean returnValue = super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX,
					scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);

			// Does all of the hard work...
			OverscrollHelper.overScrollBy(PullToRefreshHorizontalScrollView.this, deltaX, scrollX, deltaY, scrollY,
					getScrollRange(), isTouchEvent);
			if(getOnHorizontalScrollListener()!=null)
				getOnHorizontalScrollListener().onScrollV9(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
            return returnValue;
		}
		 
	 

		/**
		 * Taken from the AOSP ScrollView source
		 */
		private int getScrollRange() {
			int scrollRange = 0;
			if (getChildCount() > 0) {
				View child = getChildAt(0);
				scrollRange = Math.max(0, child.getWidth() - (getWidth() - getPaddingLeft() - getPaddingRight()));
			}
			return scrollRange;
		}
	}
	
	 
	public  class MyHorizontalScrollView extends HorizontalScrollView {
		private int mBaseScrollX;//滑动基线。也就是点击并滑动之前的x值，以此值计算相对滑动距离。  
	    private int mScreenWidth;  
	    private int mScreenHeight;  
	      
	    private LinearLayout mContainer;  
	    private boolean flag;  
	    private int mPageCount;//页面数量  
	      
	    private int mScrollX = 200;//滑动多长距离翻页  
	      
	    public MyHorizontalScrollView(Context context, AttributeSet attrs) {  
	        super(context, attrs);  
	  
	        DisplayMetrics dm = context.getApplicationContext().getResources()  
	                .getDisplayMetrics();  
	        mScreenWidth = dm.widthPixels;  
	        mScreenHeight = dm.heightPixels; 
	       
	    }  
      private boolean isScrolledToTop = true; 
		 
		@Override
	    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
	        super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
	       
	        if (scrollX == 0) {
	            isScrolledToTop = clampedX;
	        } else {
	            isScrolledToTop = false; 
	        }
	        if(getOnHorizontalScrollListener()!=null){
	             getOnHorizontalScrollListener().onLeft(scrollX == 0);
	        }
	       
	    }
	    @Override
	    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
	    	// TODO Auto-generated method stub
	    	if(getOnHorizontalScrollListener()!=null)
	    		getOnHorizontalScrollListener().onScrollX(l,oldl, getScrollX());
	    	super.onScrollChanged(l, t, oldl, oldt);
	    }
	    /** 
	     * 添加一个页面到最后。 
	     * @param page 
	     */  
	    public void addPage(View page) {  
	        addPage(page, -1);  
	    }  
	      
	    /** 
	     * 添加一个页面。 
	     * @param page 
	     */  
	    public void addPage(View page, int index) {  
	        if(!flag) {  
	            mContainer = (LinearLayout) getChildAt(0);  
	            flag = true;  
	        }  
	        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mScreenWidth, mScreenHeight);  
	        if(index == -1) {  
	            mContainer.addView(page, params);  
	        } else {  
	            mContainer.addView(page, index, params);  
	        }  
	        mPageCount++;  
	    }  
	      
	    /** 
	     * 移除一个页面。 
	     * @param index 
	     */  
	    public void removePage(int index) { 
	    	 
	        if(mPageCount < 1) {  
	            return;  
	        }  
	        if(index<0 || index>mPageCount-1) {  
	            return;  
	        }  
	        mContainer.removeViewAt(index);  
	        mPageCount--;  
	    }  
	      
	    /** 
	     * 移除所有的页面 
	     */  
	    public void removeAllPages() {  
	        if(mPageCount > 0) {  
	            mContainer.removeAllViews();  
	        }  
	    }  
	      
	    /** 
	     * 获取页面数量 
	     * @return 
	     */  
	    public int getPageCount() {  
	        return mPageCount;  
	    }  
	      
	    /** 
	     * 获取相对滑动位置。由右向左滑动，返回正值；由左向右滑动，返回负值。 
	     * @return 
	     */  
	    private int getBaseScrollX() {  
	        return getScrollX() - mBaseScrollX;  
	    }  
	      
	    /** 
	     * 使相对于基线移动x距离。 
	     * @param x x为正值时右移；为负值时左移。 
	     */  
	    private void baseSmoothScrollTo(int x) {  
	        smoothScrollTo(x + mBaseScrollX, 0);  
	        if(mOnPageListener!=null)
	         	mOnPageListener.onPage((x + mBaseScrollX)/mScreenWidth);
	    }  
	    /** 触摸时按下的点 **/
		PointF downP = new PointF();
		/** 触摸时当前的点 **/
		PointF curP = new PointF();
		int  pageId=0;
		 
	    @Override  
	    public boolean onTouchEvent(MotionEvent ev) {  

		  int action = ev.getAction();  
	        switch (action) {  
	        case MotionEvent.ACTION_DOWN:
	        	  getParent().requestDisallowInterceptTouchEvent(true);  
	        	   break;  
	        case MotionEvent.ACTION_UP:  
	        	 getParent().requestDisallowInterceptTouchEvent(true);  
	             int scrollX = getBaseScrollX();  
	             //左滑，大于一半，移到下一页  
	             if (scrollX > mScrollX) {  
	                baseSmoothScrollTo(mScreenWidth);  
	                mBaseScrollX += mScreenWidth;  
	             }   
	             //左滑，不到一半，返回原位  
	             else if (scrollX > 0) {  
	                baseSmoothScrollTo(0);  
	             }   
	             //右滑，不到一半，返回原位  
	             else if(scrollX > -mScrollX) {  
	                baseSmoothScrollTo(0);  
	            }   
	            //右滑，大于一半，移到下一页  
	            else {  
	                baseSmoothScrollTo(-mScreenWidth);  
	                mBaseScrollX -= mScreenWidth;  
	            }  
	            return true;  
	        }  
	        return super.onTouchEvent(ev);  
	    }  
	}
	private OnHorizontalScrollListener mOnHorizontalScrollListener;
	public OnHorizontalScrollListener getOnHorizontalScrollListener() {
		return mOnHorizontalScrollListener;
	}

	public void setOnHorizontalScrollListener(
			OnHorizontalScrollListener mOnHorizontalScrollListener) {
		this.mOnHorizontalScrollListener = mOnHorizontalScrollListener;
	}

 
}
